package com.example.common.interceptor;

import com.example.common.constant.SystemConstant;
import com.example.common.exception.AuthException;
import com.example.common.exception.NoLoginException;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
@Lazy
public class AuthInterceptor implements HandlerInterceptor {

    private List<String> loginAccess = Arrays.asList("common","useDic","/");// 登录后可以访问的controller

    private List<String> noLoginAccess = Arrays.asList("banner","login","logout",
            "error",
            "admin",
            "collection",
            "comment",
            "user",
            "listSong",
            "rankList",
            "singer",
            "song",
            "songList",
            "img",
            "personalized",
            "toplist",
            "recommend",
            "video",
            "search",
            "favicon.ico","/");// 不登录可以访问的controller

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        System.out.println("path" + requestURI);
        String[] pathSplit = requestURI.split("/");

        String controllerPath;
        String methodPath = "";
        if(pathSplit.length == 0){
            return true;
        }else if(pathSplit.length == 2){
            controllerPath = pathSplit[1];
        }else{
            controllerPath = pathSplit[1];
            methodPath = pathSplit[2];
        }

        if(noLoginAccess.contains(controllerPath)){
            return true;
        }else{
            Map<String,List<String>> permissionMap = (Map<String,List<String>>)request.getSession().getAttribute(SystemConstant.PERMISSION);
            if(permissionMap == null){
                if(noLoginAccess.contains(controllerPath)){
                    return true;
                }
                throw new NoLoginException("登录超时或未登录，请重新登录");
            }else{
                if(loginAccess.contains(controllerPath)){
                    return true;
                }
                if(permissionMap.keySet().contains(controllerPath)){

                    List<String> authedMethods = permissionMap.get(controllerPath);

                    if(CollectionUtils.isEmpty(authedMethods)){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    throw new AuthException("缺少访问权限");
                }
            }
        }
    }
}
